package com.yaoran.userauth.config;

import com.yaoran.userauth.config.exception.RRException;
import com.yaoran.userauth.utils.ThreadLocalUtils;
import com.yaoran.userauth.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class AuthInfoInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(AuthInfoInterceptor.class);

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        //先排除预检请求
        if(request.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())){
            return true;
        }
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String auth = request.getHeader("auth");
        logger.info(">>>>>>>拦截到api相关请求头<<<<<<<<"+auth);
        if(StringUtils.isNotEmpty(auth)){
            try {
                Map<String,String> tokenMap = tokenUtil.parseToken(auth);
                String userName = tokenMap.get("userId");
                //放到ThreadLocal中 后续直接从中获取
                ThreadLocalUtils.set("auth",auth);
                ThreadLocalUtils.set("operate",userName);
            }catch (Exception e){
                logger.error("token error", e);
                httpServletResponse.setStatus(403);
                throw new RRException("token无效",403);
            }
        }else{
            httpServletResponse.setStatus(401);
            throw new RRException("token为空",401);
        }
        return  true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        System.out.println("=====post=====");
    }

    @Override
    public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除
        ThreadLocalUtils.remove("auth");
        logger.info("移除请求头中的auth："+ThreadLocalUtils.get("auth"));
        ThreadLocalUtils.remove("operate");
    }
}
